package org.lex.ftplist.ui.util;

import java.awt.Rectangle;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Properties;
import java.util.regex.Pattern;

import javax.swing.JFrame;

import org.lex.ftplist.ui.FLApplication;
import org.lex.ftplist.util.Constants;

public class SessionUtils {
	public static void save() throws IOException {
		FLApplication app = FLApplication.getInstance();

		Properties props = new Properties();
		saveFrame(app.getMainFrame(), props);

		OutputStream out = app.getContext().getLocalStorage().openOutputFile(Constants.MY_SESSION_FILE);
		props.store(new OutputStreamWriter(out, Constants.ENCODING), "session file");
		out.close();
	}

	public static void restore() throws IOException {
		FLApplication app = FLApplication.getInstance();
		InputStream in = app.getContext().getLocalStorage().openInputFile(Constants.MY_SESSION_FILE);
		Properties props = new Properties();
		props.load(in);
		restoreFrame(app.getMainFrame(), props);
	}

	private static void saveFrame(JFrame frame, Properties props) {
		String name = frame.getName();
		// bounds
		Rectangle rect = frame.getBounds();
		props.setProperty(name + ".bounds", rect.x + "," + rect.y + "," + rect.width + "," + rect.height);
		// state
		props.setProperty(name + ".state", Integer.toString(frame.getState()));
		// ext state
		props.setProperty(name + ".extState", Integer.toString(frame.getExtendedState()));
	}

	private static Pattern COMMA_SPLITTER = Pattern.compile(Pattern.quote(","));

	private static void restoreFrame(JFrame frame, Properties props) {
		String name = frame.getName();
		// bounds
		String bv = props.getProperty(name + ".bounds", "0,0,300,200");
		String[] bvs = COMMA_SPLITTER.split(bv);
		Rectangle rect = new Rectangle();
		rect.x = Integer.parseInt(bvs[0]);
		rect.y = Integer.parseInt(bvs[1]);
		rect.width = Integer.parseInt(bvs[2]);
		rect.height = Integer.parseInt(bvs[3]);
		// frame.setBounds(rect);
		frame.setLocation(rect.x, rect.y);
		frame.setSize(rect.width, rect.height);
		// state
		int state = Integer.parseInt(props.getProperty(name + ".state", Integer.toString(JFrame.NORMAL)));
		frame.setState(state);
		// ext state
		int extState = Integer.parseInt(props.getProperty(name + ".extState", Integer.toString(JFrame.NORMAL)));
		frame.setExtendedState(extState);
	}
}
